//
//  NormalTree.swift
//  ANOA
//
//  Created by 邱仙凯 on 2024/1/18.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit

import ObjectMapper
 
// 公司树节点
var normal_Tree:NormalTreeNode?

class NormalTree: UITableViewController,UISearchBarDelegate {
    
    /// sessionK   过滤的值  传 养殖  贸易  动保  等大板块代码
    // selectedIDsArr  之前选中的节点
    static func initWithNav(showParam:String,api:API,type:OrgSelectType,sessionK:String = "",selectedIDs:[String] = [],backClosure:(([NormalTreeNode])->())?,vcClosure:((BaseNavigationController)->())?) {
        getNormalTree(api:api,sessionK: sessionK) {
            let nav = BaseNavigationController()
            let vc = NormalTree(showParam:showParam,api:api,type: type,selectedIDs: selectedIDs, backClosure: backClosure)
            nav.viewControllers = [vc]
            if let clo = vcClosure {
                clo(nav)
            }
        }
    }
    //   进来之前就选中的节点数组
    var selectedIDs = [String]()
    // 显示字段
    var showParam = ""
    var api:API!
    var type:OrgSelectType!
    var allArr = [NormalTreeNode]()
    var selectedArr = [NormalTreeNode]() // 选中的节点
    var backClosure:(([NormalTreeNode])->())?
    private var keyWord = ""
    private var searchBar:UISearchBar!
    // 子节点被搜索匹配到，自己也要现身    被选中匹配到，要处理父节点的选中逻辑
    func matchFromChildren(_ node:inout NormalTreeNode)  {
 
            if node.children.isSome {
                 
                for i in 0..<node.children!.count {
                    matchFromChildren(&node.children![i])
                }
                node.matched = node.children!.reduce(false, { (preResult, node) -> Bool in
                    preResult || node.matched
                })
                
                
                node.selected = node.children!.reduce(false, { (preResult, node) -> Bool in
                    preResult || node.selected
                })
                
            } else {
                let v = any2Str(node.dic[showParam])
                node.matched = v.contains(keyWord)
            }
       
    }
    // 选中非末节点时，需要对他的所有子节点 的选中状态同步
    func infectToChildren(_ node:inout NormalTreeNode) {
        if node.children.isSome {
            for i in 0..<node.children!.count {
                node.children![i].selected = node.selected
                infectToChildren(&node.children![i])
            }
        }
     
    }
    // 处理搜索匹配，匹配到的显示，没匹配的不显示
    func dealNode(_ node:NormalTreeNode,_ allArr:inout [NormalTreeNode]) {
        
        if keyWord == "" || (keyWord != "" && node.matched) {
            allArr.append(node)
        }
        if node.children.isSome && node.open {
            for item in  node.children! {
                dealNode(item, &allArr)
            }
        }
        
    }
    
    
    func sortData() {
        guard normal_Tree.isSome else {
            return
        }
        allArr.removeAll()
        matchFromChildren(&normal_Tree!)
        dealNode(normal_Tree!,&allArr)
    }
    // 取得选中的节点
    func getSelect(_ node:NormalTreeNode,selectedArr:inout [NormalTreeNode]) {
        if  node.selected && node.children.isNone {
            selectedArr.append(node)
        }
        if node.children.isSome {
            for item in node.children! {
                getSelect(item, selectedArr: &selectedArr)
            }
        }
    }
    
    //  初始化已选择的节点  -- 初始化的时候根据传入的已选中id数组，把选中的勾起来
    func initSelectedNode(_ node:inout NormalTreeNode) {
        node.selected = self.selectedIDs.contains(node.id ?? "-")
        if node.children.isSome {
            for i in 0..<node.children!.count {
                initSelectedNode(&node.children![i])
            }
        }
    }
    
    init(showParam:String,api:API,type:OrgSelectType,selectedIDs:[String] = [],backClosure:(([NormalTreeNode])->())?) {
        super.init(nibName: nil, bundle: nil)
        self.api = api
        self.showParam = showParam
        self.backClosure = backClosure
        self.type = type
        self.selectedIDs = selectedIDs
        guard normal_Tree.isSome else {
            return
        }
        self.initSelectedNode(&normal_Tree!)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "选择"
        
        
        
        let leftbtn = UIButton.creat4Item(title: "返回") { _ in
            self.closeAction()
        }
        let left = UIBarButtonItem(customView:leftbtn)
       
        self.navigationItem.leftBarButtonItem = left
        
        if self.type == .single {
            
        } else {
            
            let rightBtn = UIButton.creat4Item(title: "确定") { _ in
                self.selectedArr.removeAll()
                if normal_Tree.isSome {
                    self.getSelect(normal_Tree!, selectedArr: &self.selectedArr)
                    guard self.selectedArr.count > 0 else {
                        KSToast("没有选择")
                        return
                    }
                    if let clo = self.backClosure {
                        clo(self.selectedArr)
                    }
                }
                
                self.closeAction()
                
            }
            let right = UIBarButtonItem(customView: rightBtn)
            
            self.navigationItem.rightBarButtonItem = right
        }
        
        
        
        
        searchBar = UISearchBar(frame:CGRect(x:0,y:0,width:KSGlobal.screenW,height:40))
        searchBar.inputAccessoryView = KSToolbar(controller: self)
        searchBar.placeholder = "搜索"
        searchBar.delegate = self
        tableView.register(NormalTreeCell.self, forCellReuseIdentifier: NormalTreeCell.identifier)
        tableView.tableHeaderView = searchBar
        tableView.tableFooterView = UIView()
        
        tableView.rowHeight = 38
        self.sortData()
        self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
        
    }
    
    func closeAction() {
        if self.navigationController!.viewControllers.count > 1 { // 说明是push过来的
            self.navigationController?.popViewController(animated: true)
        } else {
            self.dismiss(animated: true, completion: {
            })
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return allArr.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: NormalTreeCell.identifier, for: indexPath) as? NormalTreeCell else {
            fatalError()
        }
        cell.showParam = self.showParam
        let one = allArr[indexPath.row]
        one.type = self.type
        cell.one = one
        cell.btnClosure = { [indexPath] in
                self.allArr[indexPath.row].open = !self.allArr[indexPath.row].open
            self.sortData()
            self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
        }
        cell.selectBtnClosure = { [indexPath] in
              self.allArr[indexPath.row].selected = !self.allArr[indexPath.row].selected
            if self.allArr[indexPath.row].children.isSome {
                self.infectToChildren(&self.allArr[indexPath.row])
            }
         
            self.sortData()
            self.tableView.reloadData()
        }
        cell.selectionStyle = .none
        
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let one = allArr[indexPath.row]
        
        
        if one.children.isNone {
            if self.type == .single {
                let v = any2Str(self.allArr[indexPath.row].dic[showParam])

                alertUtil(self, title: "确认选择：\(v)", operateS: [nameAction(name: "确定", action: { (_) in
                    self.comfirmAction(indexP:indexPath)
                })])
            } else {
                
            }
            
 

        } else {
            self.allArr[indexPath.row].open = !self.allArr[indexPath.row].open
            self.sortData()
            self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
        }
        
        
        
        
        
    }
    
    func comfirmAction(indexP:IndexPath) {
        if let clo = self.backClosure {
            clo([allArr[indexP.row]])
        }
        
        self.closeAction()
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        keyWord = searchText
        self.sortData()
        self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
    }
    
    
    
    
    
}

 
func getNormalTree(api:API,sessionK:String,_ success:(()->())?) {
    normal_Tree = nil
    
  
        // 待调整
    KSNetwork.shared.doRequest(api) { (data:BaseResult<NormalTreeNode>) in
            if data.flag == TRUE {
                if let infos = data.infos,infos.count > 0 {
                     var moInfo = infos

                    for i in 0..<moInfo.count {
                        moInfo[i].dic = data.infoDicArr[i]
                    }
                    
                    let aNode = moInfo.filter { $0.pId.unwrap == "" }
                    normal_Tree = aNode.first!
                    normal_Tree?.level = 0
                     dealChildren(note: &normal_Tree!, temp: moInfo,level: normal_Tree!.level!, color: .black)
                     
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
            success!()
        }
   
    
    
    
    func dealChildren(note:inout NormalTreeNode,temp:[NormalTreeNode],level:Int,color:UIColor) {
        let fNode = temp.filter { $0.pId == note.id }
        
        
//        if note.name.unwrap == "饲料事业部" {
//            note.color =   #colorLiteral(red: 0.7258723224, green: 0.4301654765, blue: 0.07145157763, alpha: 1)
//        } else if note.name.unwrap == "养殖事业部" {
//            note.color  =  #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
//        } else if note.name.unwrap == "贸易事业部" {
//            note.color  = #colorLiteral(red: 0.8745098039, green: 0.6, blue: 0.4980392157, alpha: 1)
//        }  else if note.name.unwrap == "动保事业部" {
//            note.color  = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
//        }  else if note.name.unwrap == "食品事业部" {
//            note.color  =  #colorLiteral(red: 0.6431372549, green: 0.2039215686, blue: 0.1098039216, alpha: 1)
//        } else {
//            note.color = color
//        }
        
        note.level = level
        note.children = fNode.count > 0 ? fNode : nil
        if note.children.isSome {
            for i in 0..<note.children!.count {
                dealChildren(note: &note.children![i], temp: temp, level: note.level! + 1, color: note.color ?? .black)
            }
        }
        
    }
    
}
